/* 
 * File:   TesseractExecutor.cpp
 * Author: Guilherme Monteiro
 * 
 */

#include "../headers/TesseractExecutor.h"

/**
 * Constructor of TesseractExecutor class.
 * 
 * @param cells: vector of cells
 * @param tiffImg: image with tiff extension
*/

TesseractExecutor::TesseractExecutor(vector<Cell> cells, string tiffImgPath) {
    this->tiffImgPath = tiffImgPath;
    this->cells = cells;
}

TesseractExecutor::TesseractExecutor(const TesseractExecutor& orig) {
}

TesseractExecutor::~TesseractExecutor() {
}

/**
 * Execute the tesseract to produces the
 * files with the transcriptions of each cell
 * in the image in the order of the cells are.
 * 
 */
vector<Transcription*> TesseractExecutor::runTesseract() {
    vector<Cell>::iterator itCells;
    vector<Transcription*> transcriptions;

    TessBaseAPI api;
    api.Init(NULL, LANGUAGE_CODE);
    
    Pix* pix;
    char* output;
    try {
        pix = pixRead(tiffImgPath.c_str());
        api.SetImage(pix);
    }
    catch (exception &e) {
        cerr << "Tiff image can't be loaded. Verify the image path and try again." << endl;
    }

    for(itCells = cells.begin(); itCells != cells.end(); itCells++) {
        int width = itCells->rightBottom.x - itCells->leftUpper.x;
        int height = itCells->rightBottom.y - itCells->leftUpper.y;

        api.SetRectangle(itCells->leftUpper.x, itCells->leftUpper.y,
                                        width, height);
        
        output = api.GetUTF8Text();
        
        string text = formatText(output);
        
        int confidence = api.MeanTextConf();
        
        try {
            //printf("text: %s, confidence: %d\n", text.c_str(), confidence);
            transcriptions.push_back(new Transcription(text,confidence));
        }
        catch(exception &e) {
            throw e;    
        }
        delete []output;
    }
    
    api.Clear();
    api.End();
    
    pixDestroy(&pix);
    
    return transcriptions;
}

/**
 * Returns a string without non-alfanumeric
 * characters, except to whitespace.
 * 
 * @param str: original string
 * @return string formated
 */
string TesseractExecutor::formatText(string str) {
    string fStr;
    
    for(int i = 0; i < str.length(); i++) {
        if(str[i] != '\n' && str[i] != '|') {
            fStr = fStr + str[i];
        }
    }
    return fStr;
}
